<?php

namespace app\admin\controller\sum;

use app\admin\controller\sum\Base;
use app\admin\model\sum\user\User;
use app\common\controller\Backend;
use think\Db;
use addons\sum\library\Export;
use app\admin\model\sum\user\WalletLog as UserWalletLogModel;

/**
 * 用户提现
 *
 * @icon fa fa-circle-o
 */
class UserWalletLog extends Base
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new UserWalletLogModel();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $nobuildfields = ['user_nickname', 'user_mobile'];
            list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);

            $total = $this->buildSearch()
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->buildSearch()
                ->with('user')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return $this->success('操作成功', null, $result);
        }
        return $this->view->fetch();
    }

    /**
     * 提现搜索
     *
     * @return object
     */
    public function buildSearch()
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter = $filter ? $filter : [];

        $user_nickname = isset($filter['user_nickname']) ? $filter['user_nickname'] : '';
        $user_mobile = isset($filter['user_mobile']) ? $filter['user_mobile'] : '';

        // 当前表名
        $tableName = $this->model->getQuery()->getTable();

        $applys = $this->model;

        // 购买人查询
        if ($user_nickname || $user_mobile) {
            $applys = $applys->whereExists(function ($query) use ($user_nickname, $user_mobile, $tableName) {
                $userTableName = (new \app\admin\model\User())->getQuery()->getTable();
                $query = $query->table($userTableName)->where($userTableName . '.id=' . $tableName . '.user_id');

                if ($user_nickname) {
                    $query = $query->where('nickname', 'like', "%{$user_nickname}%");
                }

                if ($user_mobile) {
                    $query = $query->where('mobile', 'like', "%{$user_mobile}%");
                }

                return $query;
            });
        }

        return $applys;
    }

    /**
     * 订单导出
     */
    public function export()
    {
        $nobuildfields = ['user_nickname', 'user_mobile'];
        list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);

        $expCellName = [
            'id' => 'ID',
            'user_phone' => '充值用户',
            'wallet' => '变动金额',
            'before' => '变动前',
            'after' => '剩余余额',
            'oper_type_text' => '操作人类型',
            'oper_name_text' => '操作人',
            'memo' => '备注',
            'createtime_text' => '交易时间',
        ];
        $export = new Export();
        $spreadsheet = null;
        $sheet = null;

        $total = $this->buildSearch()
            ->where($where)
            ->order($sort, $order)
            ->count();

        $current_total = 0;     // 当前已循环条数
        $page_size = 2000;
        $total_page = intval(ceil($total / $page_size));
        if ($total == 0) {
            $this->error('导出数据为空');
        }
        for ($i = 0; $i < $total_page; $i++) {
            $page = $i + 1;
            $is_last_page = ($page == $total_page) ? true : false;
            $list = $this->buildSearch()
                ->with('user')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $item){
                $item['user_phone']= $item['user'] ? $item['user']['mobile'] . ' ' : '';
                $item['oper_type_text']= $item['oper'] ? $item['oper']['type'] . ' ' : '';
                $item['oper_name_text']= $item['oper'] ? $item['oper']['name'] . ' ' : '';
                $item['createtime_text']= date("Y-m-d H:i:s",$item['createtime']);
            }

            $list = collection($list)->toArray();
            $current_total += count($list);     // 当前循环总条数
            $export->exportExcel('钱包记录-' . date('Y-m-d H:i:s'), $expCellName, $list, $spreadsheet, $sheet, [
                'page' => $page,
                'current_total' => $current_total,
                'is_last_page' => $is_last_page
            ]);
        }
    }

}
